package com.hzcx.app.simplechat.ui.chat;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.Switch;
import android.widget.TextView;

import com.hyphenate.chat.EMClient;
import com.hzcx.app.simplechat.R;
import com.hzcx.app.simplechat.base.BaseActivity;
import com.hzcx.app.simplechat.ui.chat.db.ChatNoticeListDao;
import com.hzcx.app.simplechat.ui.chat.event.ChatListRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatMessageListRefreshEvent;
import com.hzcx.app.simplechat.ui.chat.event.ChatSearchMsgEvent;
import com.hzcx.app.simplechat.ui.home.dao.ChatTopDao;
import com.hzcx.app.simplechat.ui.home.event.ChatTopEvent;
import com.hzcx.app.simplechat.ui.publicui.PublicConfirmDialog;
import com.hzcx.app.simplechat.ui.setting.ReportActivity;
import com.hzcx.app.simplechat.ui.user.UserInfoActivity;
import com.hzcx.app.simplechat.ui.user.bean.UserInfoBean;
import com.hzcx.app.simplechat.util.empty.EmptyUtils;
import com.hzcx.app.simplechat.util.glide.GlideUtils;
import com.hzcx.app.simplechat.view.imageview.RoundImageView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.litepal.LitePal;
import org.litepal.crud.callback.FindMultiCallback;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 聊天设置界面
 */
public class ChatSettingActivity extends BaseActivity {

    public static final String INTENT_USERINFO = "INTENT_USERINFO";

    private static final int HANDLER_DELETE = 1;

    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.iv_head)
    RoundImageView ivHead;
    @BindView(R.id.tv_nick_name)
    TextView tvNickName;
    @BindView(R.id.view_line)
    View viewLine;
    @BindView(R.id.tv_to_top)
    TextView tvToTop;
    @BindView(R.id.switch_top)
    Switch switchTop;
    @BindView(R.id.tv_notice)
    TextView tvNotice;
    @BindView(R.id.switch_notice)
    Switch switchNotice;
    @BindView(R.id.tv_search_content)
    TextView tvSearchContent;
    @BindView(R.id.tv_search_img)
    TextView tvSearchImg;
    @BindView(R.id.tv_report)
    TextView tvReport;
    @BindView(R.id.tv_clear)
    TextView tvClear;

    private UserInfoBean userInfoBean;

    @Override
    public int getLayout() {
        return R.layout.activity_chat_setting;
    }

    @Override
    public void initPresenter() {

    }

    @Override
    public void initView() {
        tvTitle.setText("聊天设置");
        userInfoBean = (UserInfoBean) getIntent().getSerializableExtra(INTENT_USERINFO);
        GlideUtils.loadImg(this, userInfoBean.getAvatar(), ivHead);
        if (EmptyUtils.isNotEmpty(userInfoBean.getRemarks_name())) {
            tvNickName.setText(userInfoBean.getRemarks_name());
        } else {
            tvNickName.setText(userInfoBean.getNickname());
        }
    }

    @Override
    public void initData() {

        // 查询消息免打扰状态
        LitePal.where("userName=?",userInfoBean.getHxusername()).findAsync(ChatNoticeListDao.class).listen(new FindMultiCallback<ChatNoticeListDao>() {
            @Override
            public void onFinish(List<ChatNoticeListDao> list) {
                if(list!=null&&list.size()>0){
                    switchNotice.setChecked(true);
                }
            }
        });

        // 消息免打扰
        switchNotice.setOnCheckedChangeListener((compoundButton, b) -> {
            if (b) {
                ChatNoticeListDao dao = new ChatNoticeListDao(userInfoBean.getHxusername());
                dao.save();
            } else {
                LitePal.deleteAll(ChatNoticeListDao.class, "userName=?", userInfoBean.getHxusername());
            }
        });

        // 查询置顶状态
        LitePal.where("userId=?", userInfoBean.getMember_id() + "").findAsync(ChatTopDao.class).listen(new FindMultiCallback<ChatTopDao>() {
            @Override
            public void onFinish(List<ChatTopDao> list) {
                if (list == null || list.size() <= 0) {
                    return;
                }
                switchTop.setChecked(true);
            }
        });

        switchTop.setOnCheckedChangeListener((compoundButton, b) -> EventBus.getDefault().post(new ChatTopEvent(userInfoBean.getMember_id(), b)));

    }

    @OnClick({R.id.tv_search_content, R.id.tv_clear, R.id.tv_report, R.id.tv_search_img, R.id.iv_head, R.id.tv_chat_history})
    public void viewOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_search_content:  // 查找聊天记录
                startActivity(new Intent(this, ChatSearchMsgActivity.class)
                        .putExtra(ChatSearchMsgActivity.INTENT_USERINFO, userInfoBean));
                break;

            case R.id.tv_clear: // 清除聊天记录
                clearMessage();
                break;

            case R.id.tv_report: // 投诉举报
                startActivity(new Intent(this, ReportActivity.class)
                        .putExtra(ReportActivity.INTENT_USER_ID, userInfoBean.getMember_id()));
                break;

            case R.id.tv_search_img: // 图片或视频
                startActivity(new Intent(this, ChatSearchImgActivity.class)
                        .putExtra(ChatSearchImgActivity.INTENT_USERINFO, userInfoBean));
                break;

            case R.id.iv_head: // 头像
                startActivity(new Intent(this, UserInfoActivity.class)
                        .putExtra(UserInfoActivity.INTENT_USER_ID, userInfoBean.getMember_id()));
                break;

            case R.id.tv_chat_history: // 历史聊天记录
                startActivity(new Intent(this, ChatHistoryActivity.class)
                        .putExtra(ChatHistoryActivity.INTENT_NICKNAME, EmptyUtils.isNotEmpty(userInfoBean.getRemarks_name()) ? userInfoBean.getRemarks_name() : userInfoBean.getNickname())
                        .putExtra(ChatHistoryActivity.INTENT_USER_ID, userInfoBean.getMember_id()));
                break;
        }
    }

    /**
     * 搜索成功，关闭界面
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void searchSuccess(ChatSearchMsgEvent event) {
        finish();
    }

    /**
     * 清除聊天记录
     */
    private void clearMessage() {

        showConfirmDialog("提示", "是否确定清除聊天记录？", null, () -> {

            showLoading();
            new Thread(() -> {
                EMClient.getInstance().chatManager().deleteConversation(userInfoBean.getHxusername(), true);
                handler.sendEmptyMessage(HANDLER_DELETE);
            }).start();


        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == HANDLER_DELETE) {
                EventBus.getDefault().post(new ChatMessageListRefreshEvent());
                EventBus.getDefault().post(new ChatListRefreshEvent());
                showError("清除成功");
                hideLoading();
            }
        }
    };
}
